package com.qcby.interceptor;

import com.qcby.entity.LoginUser;
import com.qcby.entity.Student;
import com.qcby.entity.Teacher;
import com.qcby.entity.User;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Component
public class ChatInterceptor implements HandshakeInterceptor {
    public static List<Student> studentList = new ArrayList<>();
    public static List<Teacher> teacherList = new ArrayList<>();
    public static List<Object> userList = new ArrayList<>();
    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpSession session = (HttpSession) servletRequest.getServletRequest().getSession(false);
            System.out.println(session);
            //如果用户已经登录，允许聊天
            if(session.getAttribute("teacher")!=null  && !teacherList.contains((Teacher) session.getAttribute("teacher"))){
                //获取登录的用户
                Teacher teacher = (Teacher) session.getAttribute("teacher");
                //将用户放入socket处理器的会话(WebSocketSession)中
                attributes.put("teacher", teacher);
                System.out.println("Websocket:老师[ID:" + (teacher.getId() + ",Name:"+teacher.getName()+"]要建立连接"));
                teacherList.add(teacher);
                userList.add( teacher);
            }else if(session.getAttribute("student")!=null && !studentList.contains((Student) session.getAttribute("student"))){
                //获取登录的用户
                Student student = (Student) session.getAttribute("student");
                //将用户放入socket处理器的会话(WebSocketSession)中
                attributes.put("student", student);
                System.out.println("Websocket:学生[ID:" + (student.getId() + ",Name:"+student.getName()+"]要建立连接"));
                studentList.add(student);
                userList.add(student);
            }else{
                System.out.println("--------------握手已失败...");
                return false;
            }
        }
        System.out.println(userList);
        System.out.println("--------------握手开始...");
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
        System.out.println("--------------握手成功啦...");
    }
}
